package com.luochen.cdpt.controller;

import com.luochen.cdpt.dto.FinStmtParam;
import com.luochen.cdpt.dto.OrderParam;
import com.luochen.cdpt.dto.PolicyParam;
import com.luochen.cdpt.eneity.*;
import com.luochen.cdpt.repository.*;
import com.luochen.cdpt.response.RespBean;
import com.luochen.cdpt.service.PolicyService;
import com.luochen.cdpt.util.BeanUtils;
import com.luochen.cdpt.util.Constant;
import com.luochen.cdpt.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther: star
 * @Date: 2019/1/23 13:46
 * @Description:
 */
@RestController
public class PolicyController {

    @Autowired
    IPolicyRepository policyRepository;

    @Autowired
    PolicyService policyService;

    @Autowired
    InsPlanRepository planRepository;

    @Autowired
    IEmpInfoRepository empInfoRepository;

    @Autowired
    ITeamInfoRepository teamInfoRepository;

    @Autowired
    IOrgInfoRepository orgInfoRepository;

    @Autowired
    InsPlanRepository insPlanRepository;

    @Autowired
    IFinSettlementRepository finSettlementRepository;

    @Autowired
    IPolicyFinStRelRepository policyFinStRelRepository;


    /**
     * 申请报价
     * @param ply
     * @return
     */
    @PostMapping("/submitPolicy")
    @Transactional
    public RespBean submitPolicy(@RequestBody PolicyParam ply){
        try {
            //获取订单号
            String orderNum = policyService.getOrderNum(Constant.DINGDAN_TYPE);
            //处理保单数据
            Policy policy = new Policy();
            BeanUtils.copyPropertiesNotNull(policy, ply);
            policy.setOrderid(orderNum);
            policy.setStatus("0");//待报价
            //获取当前登陆用户
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<EmpInfo> empInfos = (List<EmpInfo>)
                    empInfoRepository.findAll(QEmpInfo.empInfo.empcde.eq(user.getUsername()));
            List<TeamInfo> teamInfos =
                    (List<TeamInfo>) teamInfoRepository.findAll(QTeamInfo.teamInfo.teamcde.eq(empInfos.get(0).getTeamid()));
            policy.setTeamname(teamInfos.get(0).getTeamname());//团队名称
            policy.setTeamcde(teamInfos.get(0).getTeamcde());//团队编码
            List<OrgInfo> orgInfos =
                    (List<OrgInfo>) orgInfoRepository.findAll(QOrgInfo.orgInfo.orgcde.eq(teamInfos.get(0).getOrgcde()));
            policy.setOrgname(orgInfos.get(0).getOrgname());//机构名称
            policy.setOrgcde(orgInfos.get(0).getOrgcde());//机构编码
            policy.setCsalecde(user.getUsername());//业务员,当前登录账号
            policy.setCsalename(empInfos.get(0).getEmpname());//业务员姓名
            policyRepository.save(policy);
            //处理投保方案
            List<InsPlan> insPlans = ply.getPlanList();
            insPlans.forEach(insPlan -> {
                insPlan.setOrderid(orderNum);
            });
            planRepository.saveAll(insPlans);
            return RespBean.ok("提交成功",policy.getOrderid());
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.error("提交失败");
        }
    }

    /**
     *确认报价
     * @param param
     * @return
     */
    @PostMapping("/confrimPolicy")
    @Transactional
    public RespBean  confrimPolicy(@RequestBody Map<String,String> param){
       try {
           String orderId =  param.get("orderId");
           String status = param.get("status");//2:确认报价，4:取消报价
           Policy policy = policyRepository.findById(orderId).get();
           policy.setStatus(status);//待出单状态
           policyRepository.save(policy);
           return RespBean.ok("提交成功");
       }catch (Exception e){
           e.printStackTrace();
           return RespBean.error("提交失败");
       }
    }

    /**
     * 查询结算打包list
     * @param request
     * @return
     */
    @GetMapping("/queryFinPackagelist")
    public Page qlist(HttpServletRequest request){
        return policyService.qlist(request);
    }

    /**
     * 补录信息保存、报价、出单
     * @param ply
     * @return
     */
    @PatchMapping("/dealOrder")
    @Transactional
    public RespBean dealOrder(@RequestBody PolicyParam ply) {
        try {
            String orderId = ply.getOrderid();
            if(StringUtils.isEmptry(orderId))
                return RespBean.error("订单号不能为空");
            Policy policy = policyRepository.findById(orderId).get();
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<EmpInfo> empInfos = (List<EmpInfo>)
                    empInfoRepository.findAll(QEmpInfo.empInfo.empcde.eq(user.getUsername()));
            if (StringUtils.isEmptry(ply.getStatus()))
                return RespBean.error("订单处理状态不能为空");
            if("1".equals(ply.getStatus())){
                policy.setBjrcde(user.getUsername());
                policy.setBjrname(empInfos.get(0).getEmpname());
            }else if("3".equals(ply.getStatus())){
                policy.setCopercde(user.getUsername());
                policy.setCopername(empInfos.get(0).getEmpname());
            }
            BeanUtils.copyPropertiesNotNull(policy, ply);
            policyRepository.save(policy);
            List<InsPlan> planList = ply.getPlanList();
            if (null != planList && planList.size() > 0) {
                for (InsPlan insPlan : planList) {
                    InsPlan plan = insPlanRepository.findById(insPlan.getId()).get();
                    BeanUtils.copyPropertiesNotNull(plan, insPlan);
                    insPlanRepository.save(plan);
                }
            }
            return RespBean.ok("处理成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.error("处理失败");
        }
    }

    /**
     * 订单打包处理
     * @param param
     * @return
     */
    @PostMapping("/packageOrder")
    @Transactional
    public RespBean packageOrder(@RequestBody OrderParam param){
        try {
            String empcde = param.getEmpcde();
            List<EmpInfo> empInfos = (List<EmpInfo>)
                    empInfoRepository.findAll(QEmpInfo.empInfo.empcde.eq(empcde));
            if (null == empInfos || empInfos.size() == 0) return RespBean.error("未找到该员工：" + empcde + "信息！");
            EmpInfo empInfo = empInfos.get(0);
            //保存结算信息
            FinSettlement finSettlement = new FinSettlement();
            String finsltno = policyService.getOrderNum(Constant.JIESUANDAN_TYPE);
            finSettlement.setFinsltno(finsltno);//结算单号
            finSettlement.setEmpcde(empcde);//提现人工号
            finSettlement.setEmpname(param.getEmpname());//提现人名称
            //团队信息
            List<TeamInfo> teamInfos =
                    (List<TeamInfo>) teamInfoRepository.findAll(QTeamInfo.teamInfo.teamcde.eq(empInfo.getTeamid()));
            finSettlement.setTeamname(teamInfos.get(0).getTeamname());//团队名称
            finSettlement.setTeamcde(teamInfos.get(0).getTeamcde());//团队编码
            finSettlement.setBankaccname(empInfo.getBankaccname());//开户人名称
            finSettlement.setBankaccount(empInfo.getBankaccount());//卡号
            finSettlement.setBankname(empInfo.getBankname());//开户银行
            finSettlement.setSfbrjs(param.getSfbrjs());//是否本人结算
            finSettlement.setFee(param.getFee());
            finSettlement.setStatus("0");//待处理
            this.finSettlementRepository.save(finSettlement);
            //保存订单和结算表关联信息
            List<Policy> list = param.getOrders();
            for (Policy policy : list) {
                PolicyFinStRel policyFinStRel = new PolicyFinStRel();
                policyFinStRel.setCash(policy.getDjsfee());
                policyFinStRel.setOrderid(policy.getOrderid());
                policyFinStRel.setFinsltno(finsltno);
                policyFinStRel.setStatus("0");
                this.policyFinStRelRepository.save(policyFinStRel);
                //更新订单表
                Policy ply = policyRepository.findById(policy.getOrderid()).get();
                ply.setDjsfee(0d);//待结算金额为0
                ply.setFsmtfee(policy.getDjsfee());//已结算金额
                ply.setFsmtstatus("0");
                this.policyRepository.save(ply);
            }
            return RespBean.ok("提交成功！");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.error("提交失败!");
        }
    }

    /**
     * 结算处理
     * @param param
     * @return
     */
    @PostMapping("/dealFinStmt")
    @Transactional
    public RespBean dealFinStmt(@RequestBody FinStmtParam param) {
        try {
            String type = param.getType();
            String finsltno = param.getFinsltno();
            FinSettlement finSettlement = finSettlementRepository.findById(finsltno).get();
            if (Constant.FIN_TYPE_0.equals(type)) {
                finSettlement.setStatus("1");//已处理
                finSettlement.setOpertm(new Date());
                User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                List<EmpInfo> empInfos = (List<EmpInfo>)
                        empInfoRepository.findAll(QEmpInfo.empInfo.empcde.eq(user.getUsername()));
                finSettlement.setCopercde(user.getUsername());
                finSettlement.setCopername(empInfos.get(0).getEmpname());
                finSettlementRepository.save(finSettlement);
                List<PolicyFinStRel> list = (List<PolicyFinStRel>) policyFinStRelRepository.findAll(QPolicyFinStRel.
                        policyFinStRel.finsltno.eq(finsltno));
                //更新关联表状态为已处理
                if (null != list && list.size() > 0) {
                    list.forEach(policyFinStRel -> {
                        policyFinStRel.setStatus("1");
                    });
                    policyFinStRelRepository.saveAll(list);
                }
            } else if (Constant.FIN_TYPE_1.equals(type)) {
                //删除该单
                finSettlementRepository.delete(finSettlement);
                //删除关联表信息
                List<PolicyFinStRel> list = (List<PolicyFinStRel>) policyFinStRelRepository.findAll(QPolicyFinStRel.
                        policyFinStRel.finsltno.eq(finsltno));
                //更新policy表待结算金额
                for (PolicyFinStRel rel : list) {
                    Policy ply = policyRepository.findById(rel.getOrderid()).get();
                    ply.setDjsfee(rel.getCash());//待结算金额为0
                    ply.setFsmtfee(0d);//已结算金额
                    this.policyRepository.save(ply);
                }
                policyFinStRelRepository.deleteAll(list);
            }
            return RespBean.ok("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error("提交失败");
        }
    }

    /**
     * 查询财务统计列表
     * @return
     */
    @GetMapping("/queryFinList")
    public Page queryFinList(HttpServletRequest request){
           return policyService.queryFinList(request);
    }
}
